/*
 * @Date: 2025-11-07 18:06:16
 * @Auth: 873768511@qq.com
 * @LastEditors: 873768511@qq.com
 * @LastEditTime: 2025-11-11 15:04:12
 * @FilePath: \corpus\src\pages\systemManagement\menu\utils\index.ts
 */
import type { IAppMenuDO } from '@/types/systemManagement/menu';
import { MenuTypeEnum } from '@/types/systemManagement/menu';
import type { IEnums } from '@/types/global';

/**
 * 对菜单列表进行排序
 * @param menuList 要排序的菜单树
 * @returns 排序后的菜单树
 */
export function sortMenu(menuList: IAppMenuDO[]): IAppMenuDO[] {
  menuList?.forEach((item) => {
    if (item?.children) {
      sortMenu(item.children);
    }
  });
  menuList.sort((a, b) => a.menuSort - b.menuSort);
  return menuList;
}

/**
 * 过滤按钮类型的菜单树
 * @param treeData 要过滤的菜单树
 * @returns 过滤后的菜单树
 */
export function filterBtn(treeData?: IAppMenuDO[]): IAppMenuDO[] {
  if (!treeData) {
    return [];
  }
  return treeData
    .filter(
      (item) =>
        item.children?.length || item.menuType as string !== MenuTypeEnum.BTN,
    )
    .map((item) =>
      item.children?.length ? { ...item, children: filterBtn(item.children) } : item,
    );
}

/**
 * 根据menuList和id查找对应的菜单节点
 * @param menuList 菜单列表
 * @param id 菜单id
 * @returns 找到的菜单节点 | 未找到返回undefined
 */
export function findMenuById(menuList?: IAppMenuDO[], id?: number): IAppMenuDO | undefined {
  if (!menuList || !id) {
    return undefined;
  }
  let node: IAppMenuDO | undefined = undefined;
  // 遍历菜单列表
  menuList?.forEach((item) => {
    if (item?.id === id) {
      node = item;
    }
    if (item?.children?.length) {
      const childNode = findMenuById(item.children, id);
      if (childNode) {
        node = childNode;
      }
    }
  });
  return node;
}

/**
 * 根据menuList和parentId查找其子节点
 * @param menuList 菜单列表
 * @param parentId
 * @returns 找到的菜单节点的children列表 | 未找到返回undefined
 */
export function findChildrenKeyListByParentId(
  menuList?: IAppMenuDO[],
  parentId?: number,
): number[] | undefined {
  if (!menuList || !Number.isFinite(parentId)) {
    return undefined;
  }
  if (parentId === 0) {
    return menuList?.map((item) => item.id);
  }
  let nodeList: IAppMenuDO[] | undefined = [];
  // 遍历菜单列表
  menuList?.forEach((item) => {
    if (item?.id === parentId) {
      nodeList = item?.children;
    }
    if (item?.children?.length) {
      const childNode = findMenuById(item.children, parentId);
      if (childNode) {
        nodeList = childNode?.children;
      }
    }
  });
  return nodeList?.map((item) => item.id);
}
